<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\AppBaseController;
use App\Models\ParkInfo;
use App\Models\Video;
use Illuminate\Http\Request;
use DB;
use App\Models\{VplRecord,ParkRecord,ParkChannels,PayFee,CardInfo,BadCarLog,OfflineUser};
use Illuminate\Support\Facades\URL;
use Storage;
use Schema;

class ParkRecordAPIController extends AppBaseController
{

    private $park_arr = [];
    private $host;

    public function __construct()
    {
        $park_arr = $this->getUserParks();
        $park_arr = $this->getParkCodes($park_arr);
        $this->park_arr = $park_arr;
        $this->host = URL::previous();
    }

    /**
     * 车场列表
     *
     * @param Request $request
     * @return mixed
     *
     *
     * 139 入口  140 出口
     */
    public function index(Request $request)
    {
        $input = $request->all();
        $field = $input['field']??'out_time';
        $sort = $input['sort']??'DESC';
        $page = $input['page']??1;
        $pages = $input['limit']??15;
        $input['park_code'] = $input['park_code']??'';
        $all_pay_type = config('pay');
        // 获取车场记录
        $park_name = ParkChannels::select(['name','arm_code'])->select('park_code',"name",'arm_code','type')->get()->toArray();
        $park_name_arr = [];
        foreach ($park_name as $p) {
            $park_name_arr[$p['park_code']][$p['arm_code']][$p['type']] = $p['name'];
        }
        $p = new ParkRecord();
        $p->setTable("t_park_record_{$input['park_code']}");

        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $p = $p->where("park_code", $input['park_code']);
        } else {
            return $this->sendError('车场不能为空');
        }
        // 车辆状态
        if(isset($input['status']) && !empty($input['status'])){
            $p = $p->where("status", $input['status']);
        }
        // 车辆号码
        if(isset($input['vpl_number']) && !empty($input['vpl_number'])){
            $input['vpl_number'] = strtoupper($input['vpl_number']);
            $p = $p->where("vpl_number", 'like', '%'.$input['vpl_number'].'%');
        }
        // 车主名称
        if(isset($input['vpl_owner']) && !empty($input['vpl_owner'])){
            $p = $p->where("vpl_owner",'like','%'.$input['vpl_owner'].'%');
        }
        // 入口名称
        if(isset($input['in_arm_code']) && is_numeric($input['in_arm_code'])){
            $p = $p->where("in_arm_code", $input['in_arm_code']);
        }
        // 进场时间
        if(isset($input['in_time']) && !empty($input['in_time'])){
            $start_time_min = $input['in_time'][0]?($input['in_time'][0]):'';
            $start_time_max = $input['in_time'][1]?($input['in_time'][1]):'';
            if($start_time_min){
                $p = $p->where("in_time", '>=' ,$start_time_min);
            }
            if($start_time_max){
                $p = $p->where("in_time", '<=' ,$start_time_max);
            }
        }
        // 进车类型
        if(isset($input['vpl_type']) && !empty($input['vpl_type'])){
            $p = $p->where("vpl_type", $input['vpl_type']);
        }
        // 出口名称
        if(isset($input['out_arm_code']) && is_numeric($input['out_arm_code'])){
            $p = $p->where("out_arm_code", $input['out_arm_code']);
        }
        // 出场时间
        if(isset($input['out_time']) && !empty($input['out_time'])){
            $end_time_min = $input['out_time'][0]?($input['out_time'][0]):'';
            $end_time_max = $input['out_time'][1]?($input['out_time'][1]):'';
            if($end_time_min){
                $p = $p->where("out_time", '>=' ,$end_time_min);
            }
            if($end_time_max){
                $p = $p->where("out_time", '<=' ,$end_time_max);
            }
        }
        // 应收金额
        if(isset($input['parking_charge_min']) && !empty($input['parking_charge_min'])){
            $p = $p->where("calc_charge", '>=' ,$input['parking_charge_min']*100);
        }
        if(isset($input['parking_charge_max']) && !empty($input['parking_charge_max'])){
            $p = $p->where("calc_charge", '<=' , $input['parking_charge_max']*100);
        }
        // 实收金额
        if(isset($input['total_charge_min']) && !empty($input['total_charge_min'])){
            $p =  $p->where("parking_charge", '>=' , $input['total_charge_min']*100);
        }
        if(isset($input['total_charge_max']) && !empty($input['total_charge_max'])){
            $p =  $p->where("parking_charge", '<=' ,$input['total_charge_max']*100);
        }
        // 停车时长
        if(isset($input['parking_duration_min']) && !empty($input['parking_duration_min'])){
            $p =  $p->where("parking_duration", '>=' ,$input['parking_duration_min']*60);
        }
        if(isset($input['parking_duration_max']) && !empty($input['parking_duration_max'])){
            $p = $p->where("parking_duration", '<=' ,$input['parking_duration_max']*60);
        }
        // 车类型
        if(isset($input['car_type']) && is_numeric($input['car_type'])){
            if($input['car_type'] == 1) {
                $p = $p->whereRaw('LENGTH(vpl_number)<15');
            } else {
                $p = $p->whereRaw('LENGTH(vpl_number)>=15');
            }
        }

        $file_name = md5('index_detail_' . json_encode($input)) . ".csv";
        if (isset($input['export']) && !empty($input['export'])) {
            if(!isset($input['out_time'])){
                return  $this->sendError('请选出场时间范围');
            }
            if(($input['out_time'][1]-$input['out_time'][0])>24*3600*7){
                return  $this->sendError('时间超出范围');
            }
            if (file_exists(storage_path("app/public/" . $file_name))) {
                $res = [];
                $res['file_name'] = $file_name;
                return $this->sendResponse($res, '查询成功');
            }
            $record = $p->get();
        } else {
            $record = $p->orderBy($field,$sort)->paginate($pages,array("*"),"page",$page);
        }

        $type_arr = config('custom.auth_type');
        foreach ($record as &$val) {
            if(strlen($val->vpl_number) >= 15 || empty($val->vpl_number)){
                $val->car_type = '无车牌';
            } else {
                $val->car_type = '有车牌';
            }
            $val->parking_duration = sec2time($val->parking_duration);

            $val->in_name = $park_name_arr[$val->park_code][$val->in_arm_code][139]??'';
            $val->out_name = $park_name_arr[$val->park_code][$val->out_arm_code][140]??'';
            $val->charge_info = '';
            if($val->charge_items) {
                $pay_arr = json_decode(stripslashes($val->charge_items), true);
                if($pay_arr) {
                    foreach ($pay_arr as $v) {
                        $charger = OfflineUser::where("name", $v['charger']??'')->value("true_name");
                        $money_str = '';
                        if (isset($v['account'])) {
                            $money_str = "金额：" . (number_format(($v['account']??0) / 100, 2, '.', '')) . "元,";
                        } elseif (isset($v['shishou'])) {
                            if(isset($v['charge_type']) && $v['charge_type'] == 6){
                                $money_str = "面额：" . (sec2time($v['shishou']*60??0,false)) . ",";
                            } else {
                                $money_str = "应收金额：" . (number_format(($v['yingshou']??0) / 100, 2, '.', '')) . "元,
                        实收金额：" . (number_format(($v['shishou']??0) / 100, 2, '.', '')) . "元,";
                            }
                        }
                        $val->charge_info .= $money_str . "收费类型：" . ($all_pay_type[$v['charge_type']]??'') . ",收费员：" . $charger . "(" . ($v['charger']??0) . "),时间：" . ((isset($v['time']))?date("Y-m-d H:i", $v['time']):'') . ";";
                    }
                    $val->charge_info = trim($val->charge_info, ';');
                }
            } else {
                $val->charge_info = '';
            }
            if(empty($val->out_time)){
                $val->parking_charge = '';
                $val->total_charge = '';
                $val->calc_charge = '';
                $val->parking_duration = '';
            } else {
                $val->parking_charge = number_format($val->parking_charge / 100, 2, '.', '');
                $val->total_charge = number_format($val->total_charge / 100, 2, '.', '');
                $val->calc_charge = number_format($val->calc_charge / 100, 2, '.', '');
            }
            $val->in_time = $val->in_time?date("Y-m-d H:i:s", $val->in_time):'';
            $val->out_time = $val->out_time?date("Y-m-d H:i:s", $val->out_time):'';
            $val->vpl_type = isset($type_arr[$val->vpl_type])?$type_arr[$val->vpl_type]:'';
        }
        if(isset($input['export']) && !empty($input['export'])){
            $title = ['vpl_number'=>'车牌号码','in_name'=>'入口名称','in_time'=>'进场时间','out_name'=>'出口名称','out_time'=>'出场时间',
                'parking_duration'=>'停车时长','total_chatge'=>'实收金额(元)'];
            $export_data = [];
            foreach ($record as $val) {
                $tmp = [];
                $tmp['vpl_number'] = $val['vpl_number'];
                $tmp['in_name'] = $val['in_name'];
                $tmp['in_time'] = $val['in_time'];
                $tmp['out_name'] = $val['out_name'];
                $tmp['out_time'] = $val['out_time'];
                $tmp['parking_duration'] = $val['parking_duration'];
                $tmp['parking_charge'] = $val['parking_charge'];
                $export_data[] = $tmp;
            }
            return $this->export($export_data,$title,$file_name);
        }
        return $this->sendResponse($record, '查询成功');
    }


    /**
     *  信息部要求数据
     * @param Request $request
     * @return mixed
     */
    public function records(Request $request)
    {
        $token = $request->post("token");
        if($token != '7c58419343baed82b4b623f2ca7b395a'){
            return $this->sendError('验证不对');
        }
        $input = $request->all();
        $field = $input['field']??'out_time';
        $sort = $input['sort']??'DESC';
        $page = $input['page']??1;
        $pages = $input['limit']??15;
        $input['park_code'] = $input['park_code']??'';
        $all_pay_type = config('pay');
        // 获取车场记录
        $park_name = ParkChannels::select(['name','arm_code'])->select('park_code',"name",'arm_code','type')->get()->toArray();
        $park_name_arr = [];
        foreach ($park_name as $p) {
            $park_name_arr[$p['park_code']][$p['arm_code']][$p['type']] = $p['name'];
        }
        $p = new ParkRecord();
        $p->setTable("t_park_record_{$input['park_code']}");

        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $p = $p->where("park_code", $input['park_code']);
        } else {
            return $this->sendError('车场不能为空');
        }
        // 车辆状态
        if(isset($input['status']) && !empty($input['status'])){
            $p = $p->where("status", $input['status']);
        }
        // 车辆号码
        if(isset($input['vpl_number']) && !empty($input['vpl_number'])){
            $input['vpl_number'] = strtoupper($input['vpl_number']);
            $p = $p->where("vpl_number", 'like', '%'.$input['vpl_number'].'%');
        }
        // 车主名称
        if(isset($input['vpl_owner']) && !empty($input['vpl_owner'])){
            $p = $p->where("vpl_owner",'like','%'.$input['vpl_owner'].'%');
        }
        // 入口名称
        if(isset($input['in_arm_code']) && is_numeric($input['in_arm_code'])){
            $p = $p->where("in_arm_code", $input['in_arm_code']);
        }
        // 进场时间
        if(isset($input['in_time']) && !empty($input['in_time'])){
            $start_time_min = $input['in_time'][0]?($input['in_time'][0]):'';
            $start_time_max = $input['in_time'][1]?($input['in_time'][1]):'';
            if($start_time_min){
                $p = $p->where("in_time", '>=' ,$start_time_min);
            }
            if($start_time_max){
                $p = $p->where("in_time", '<=' ,$start_time_max);
            }
        }
        // 进车类型
        if(isset($input['vpl_type']) && !empty($input['vpl_type'])){
            $p = $p->where("vpl_type", $input['vpl_type']);
        }
        // 出口名称
        if(isset($input['out_arm_code']) && is_numeric($input['out_arm_code'])){
            $p = $p->where("out_arm_code", $input['out_arm_code']);
        }
        // 出场时间
        if(isset($input['out_time']) && !empty($input['out_time'])){
            $end_time_min = $input['out_time'][0]?($input['out_time'][0]):'';
            $end_time_max = $input['out_time'][1]?($input['out_time'][1]):'';
            if($end_time_min){
                $p = $p->where("out_time", '>=' ,$end_time_min);
            }
            if($end_time_max){
                $p = $p->where("out_time", '<=' ,$end_time_max);
            }
        }
        // 应收金额
        if(isset($input['parking_charge_min']) && !empty($input['parking_charge_min'])){
            $p = $p->where("calc_charge", '>=' ,$input['parking_charge_min']*100);
        }
        if(isset($input['parking_charge_max']) && !empty($input['parking_charge_max'])){
            $p = $p->where("calc_charge", '<=' , $input['parking_charge_max']*100);
        }
        // 实收金额
        if(isset($input['total_charge_min']) && !empty($input['total_charge_min'])){
            $p =  $p->where("parking_charge", '>=' , $input['total_charge_min']*100);
        }
        if(isset($input['total_charge_max']) && !empty($input['total_charge_max'])){
            $p =  $p->where("parking_charge", '<=' ,$input['total_charge_max']*100);
        }
        // 停车时长
        if(isset($input['parking_duration_min']) && !empty($input['parking_duration_min'])){
            $p =  $p->where("parking_duration", '>=' ,$input['parking_duration_min']*60);
        }
        if(isset($input['parking_duration_max']) && !empty($input['parking_duration_max'])){
            $p = $p->where("parking_duration", '<=' ,$input['parking_duration_max']*60);
        }
        // 车类型
        if(isset($input['car_type']) && is_numeric($input['car_type'])){
            if($input['car_type'] == 1) {
                $p = $p->whereRaw('LENGTH(vpl_number)<15');
            } else {
                $p = $p->whereRaw('LENGTH(vpl_number)>=15');
            }
        }

        $file_name = md5('index_detail_' . json_encode($input)) . ".csv";
        if (isset($input['export']) && !empty($input['export'])) {
            if(!isset($input['out_time'])){
                return  $this->sendError('请选出场时间范围');
            }
            if(($input['out_time'][1]-$input['out_time'][0])>24*3600*7){
                return  $this->sendError('时间超出范围');
            }
            if (file_exists(storage_path("app/public/" . $file_name))) {
                $res = [];
                $res['file_name'] = $file_name;
                return $this->sendResponse($res, '查询成功');
            }
            $record = $p->get();
        } else {
            $record = $p->orderBy($field,$sort)->paginate($pages,array("*"),"page",$page);
        }

        $type_arr = config('custom.auth_type');
        foreach ($record as &$val) {
            if(strlen($val->vpl_number) >= 15 || empty($val->vpl_number)){
                $val->car_type = '无车牌';
            } else {
                $val->car_type = '有车牌';
            }
            $val->parking_duration = sec2time($val->parking_duration);
            $val->in_name = $park_name_arr[$val->park_code][$val->in_arm_code][139]??'';
            $val->out_name = $park_name_arr[$val->park_code][$val->out_arm_code][140]??'';
            $val->charge_info = '';
            if($val->charge_items) {
                $pay_arr = json_decode(stripslashes($val->charge_items), true);
                if($pay_arr) {
                    foreach ($pay_arr as $v) {
                        $charger = OfflineUser::where("name", $v['charger']??'')->value("true_name");
                        $money_str = '';
                        if (isset($v['account'])) {
                            $money_str = "金额：" . (number_format(($v['account']??0) / 100, 2, '.', '')) . "元,";
                        } elseif (isset($v['shishou'])) {
                            if(isset($v['charge_type']) && $v['charge_type'] == 6){
                                $money_str = "面额：" . (sec2time($v['shishou']*60??0,false)) . ",";
                            } else {
                                $money_str = "应收金额：" . (number_format(($v['yingshou']??0) / 100, 2, '.', '')) . "元,
                        实收金额：" . (number_format(($v['shishou']??0) / 100, 2, '.', '')) . "元,";
                            }
                        }
                        $val->charge_info .= $money_str . "收费类型：" . ($all_pay_type[$v['charge_type']]??'') . ",收费员：" . $charger . "(" . ($v['charger']??0) . "),时间：" . ((isset($v['time']))?date("Y-m-d H:i", $v['time']):'') . ";";
                    }
                    $val->charge_info = trim($val->charge_info, ';');
                }
            } else {
                $val->charge_info = '';
            }
            if(empty($val->out_time)){
                $val->parking_charge = '';
                $val->total_charge = '';
                $val->calc_charge = '';
                $val->parking_duration = '';
            } else {
                $val->parking_charge = number_format($val->parking_charge / 100, 2, '.', '');
                $val->total_charge = number_format($val->total_charge / 100, 2, '.', '');
                $val->calc_charge = number_format($val->calc_charge / 100, 2, '.', '');
            }
            $val->in_time = $val->in_time?date("Y-m-d H:i:s", $val->in_time):'';
            $val->out_time = $val->out_time?date("Y-m-d H:i:s", $val->out_time):'';
            $val->vpl_type = isset($type_arr[$val->vpl_type])?$type_arr[$val->vpl_type]:'';
        }
        if(isset($input['export']) && !empty($input['export'])){
            $title = ['vpl_number'=>'车牌号码','in_name'=>'入口名称','in_time'=>'进场时间','out_name'=>'出口名称','out_time'=>'出场时间',
                'parking_duration'=>'停车时长','total_chatge'=>'实收金额(元)'];
            $export_data = [];
            foreach ($record as $val) {
                $tmp = [];
                $tmp['vpl_number'] = $val['vpl_number'];
                $tmp['in_name'] = $val['in_name'];
                $tmp['in_time'] = $val['in_time'];
                $tmp['out_name'] = $val['out_name'];
                $tmp['out_time'] = $val['out_time'];
                $tmp['parking_duration'] = $val['parking_duration'];
                $tmp['parking_charge'] = $val['parking_charge'];
                $export_data[] = $tmp;
            }
            return $this->export($export_data,$title,$file_name);
        }
        return $this->sendResponse($record, '查询成功');
    }


    /**
     * 车场列表
     *
     * @param Request $request
     * @return mixed
     */
    public function recordDetail(Request $request)
    {
        $input = $request->all();
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;
        $all_pay_type = config('pay');
        $input['park_code'] = $request->input('park_code','');
        // 获取车场记录
        $park_name = ParkChannels::select(['name','arm_code'])->select('park_code',"name",'arm_code','type')->get()->toArray();
        $park_name_arr = [];
        foreach ($park_name as $p) {
            $park_name_arr[$p['park_code']][$p['arm_code']][$p['type']] = $p['name'];
        }
        $p = new ParkRecord();
        $p->setTable("t_park_record_{$input['park_code']}");


        $p = $p->where(function ($query) {
            $key1 = '"charge_type":1';
            $key2 = '"charge_type":50';
            $query->orWhere(function ($query) use ($key1) {
                    $query->where('charge_items', 'like', "%$key1%");
                })
                ->orWhere(function ($query) use ($key2) {
                    $query->where('charge_items', 'like', "%$key2%");
                });
        });
        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $p = $p->where("park_code", $input['park_code']);
        } else {
            return $this->sendError('车场不能为空');
        }

        // 出场时间
        if(isset($input['vtime']) && !empty($input['vtime'])){
            $end_time_min = $input['vtime'][0]?($input['vtime'][0]):'';
            $end_time_max = $input['vtime'][1]?($input['vtime'][1]):'';
            if($end_time_min){
                $p = $p->where("out_time", '>=' ,$end_time_min);
            }
            if($end_time_max){
                $p = $p->where("out_time", '<=' ,$end_time_max);
            }
        }
        $file_name = md5('record_detail_' . json_encode($input)) . ".csv";
        if (isset($input['export']) && !empty($input['export'])) {
            if (file_exists(storage_path("app/public/" . $file_name))) {
                $res = [];
                $res['file_name'] = $file_name;
                return $this->sendResponse($res, '查询成功');
            }
            $record = $p->get();
        } else {
            $record = $p->orderBy("in_time",'desc')->paginate($pages,array("*"),"page",$page);
        }
        $type_arr = config('custom.auth_type');
        foreach ($record as &$val) {
            if(strlen($val->vpl_number) >= 15 || empty($val->vpl_number)){
                $val->car_type = '无车牌';
            } else {
                $val->car_type = '有车牌';
            }
            $val->parking_duration = sec2time($val->parking_duration);

            $val->in_name = $park_name_arr[$val->park_code][$val->in_arm_code][139]??'';
            $val->out_name = $park_name_arr[$val->park_code][$val->out_arm_code][140]??'';
            $val->pay_type_name = '';
            $val->charger = '';
            $val->charge_info = '';
            if($val->charge_items) {
                $pay_arr = json_decode(stripslashes($val->charge_items), true);
                if($pay_arr) {
                    foreach ($pay_arr as $v) {
                        $charger = OfflineUser::where("name", $v['charger']??'')->value("true_name");
                        $money_str = '';
                        if (isset($v['account'])) {
                            $money_str = "金额：" . (number_format(($v['account']??0) / 100, 2, '.', '')) . "元,";
                        } elseif (isset($v['shishou'])) {
                            if(isset($v['charge_type']) && $v['charge_type'] == 6){
                                $money_str = "面额：" . (sec2time($v['shishou']*60??0,false)) . ",";
                            } else {
                                $money_str = "应收金额：" . (number_format(($v['yingshou']??0) / 100, 2, '.', '')) . "元,
                        实收金额：" . (number_format(($v['shishou']??0) / 100, 2, '.', '')) . "元,";
                            }
                        }
                        $val->charge_info .= $money_str . "收费类型：" . ($all_pay_type[$v['charge_type']]??'') . ",收费员：" . $charger . "(" . ($v['charger']??0) . "),时间：" . ((isset($v['time']))?date("Y-m-d H:i", $v['time']):'') . ";";
                    }
                    $val->charge_info = trim($val->charge_info, ';');
                }
            } else {
                $val->charge_info = '';
            }
            $val->charge_info = trim($val->charge_info,';');
            $val->pay_type_name = trim($val->pay_type_name,';');
            $val->charger = trim($val->charger,';');
            $val->parking_charge = number_format($val->parking_charge/100,2,'.','');
            $val->total_charge = number_format($val->total_charge/100,2,'.','');
            $val->calc_charge = number_format($val->calc_charge/100,2,'.','');
            $val->in_time = $val->in_time?date("Y-m-d H:i:s", $val->in_time):'';
            $val->out_time = $val->out_time?date("Y-m-d H:i:s", $val->out_time):'';
            $val->vpl_type = isset($type_arr[$val->vpl_type])?$type_arr[$val->vpl_type]:'';
        }
        if(isset($input['export']) && !empty($input['export'])){
            $title = ['vpl_number'=>'车牌号码','charger'=>'收费员','in_name'=>'入口名称','in_time'=>'进场时间','out_name'=>'出口名称','out_time'=>'出场时间',
                'parking_duration'=>'停车时长','status'=>'支付方式','total_chatge'=>'实收金额(元)','charge_info'=>'收费详情'];
            $export_data = [];
            foreach ($record as $val) {
                $tmp = [];
                $tmp['vpl_number'] = $val['vpl_number'];
                $tmp['charger'] = $val['charger'];
                $tmp['in_name'] = $val['in_name'];
                $tmp['in_time'] = $val['in_time'];
                $tmp['out_name'] = $val['out_name'];
                $tmp['out_time'] = $val['out_time'];
                $tmp['parking_duration'] = $val['parking_duration'];
                $tmp['status'] = $val['status'];
                $tmp['parking_charge'] = $val['parking_charge'];
                $tmp['total_charge'] = $val['total_charge'];
                $tmp['charge_info'] = $val['charge_info'];
                $export_data[] = $tmp;
            }
            return $this->export($export_data,$title,$file_name);
        }
        return $this->sendResponse($record, '查询成功');
    }


    /**
     * etc车场列表
     *
     * @param Request $request
     * @return mixed
     */
    public function etcRecord(Request $request)
    {
        $input = $request->all();
        $input['park_code'] = $request->input('park_code','');
        // 获取车场记录

        $etc_park = config('custom.etc_park');
        $arm_etc = config('custom.etc_park_arm');
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $tmp = [];
            foreach ($input['park_code'] as $v) {
                if(in_array($v,$etc_park)){
                    $tmp[$arm_etc[$v]] = $v;
                }
            }
            $etc_park = $tmp;
        }
        $num_arr = [];
        foreach ($etc_park as $k=>$e) {
            $p = new ParkRecord();
            $p->setTable("t_park_record_{$e}");
            // 出场时间
            if(isset($input['vtime']) && !empty($input['vtime'])){
                $end_time_min = $input['vtime'][0]?($input['vtime'][0]):'';
                $end_time_max = $input['vtime'][1]?($input['vtime'][1]):'';
                if($end_time_min){
                    $p = $p->where("out_time", '>=' ,$end_time_min);
                }
                if($end_time_max){
                    $p = $p->where("out_time", '<=' ,$end_time_max);
                }
            }
            $num_arr[] = $p->where("out_arm_code",$k)->where("status",2)->count();
        }
        $num = array_sum($num_arr);
        return $this->sendResponse($num, '查询成功');
    }

    /*
     *  停车记录详情
     */
    public function info(Request $request){
        $park_code = $request->input('park_code');
        $id = $request->input('id');
        $where = " where 1=1 ";
        if(empty($park_code)){
            return $this->sendError('车场code不能为空');
        }
        if(!empty($id)){
            $where .= " and id='{$id}'";
        } else{
            return $this->sendError('车场id不能为空');
        }
        $limit = " limit 1";
        $p = new ParkRecord();
        $p->setTable("t_park_record_{$park_code}");
        $record = $p->find($id);

        if($record) {
            if (strlen($record->vpl_number) >= 15 || empty($record->vpl_number)) {
                $record->car_type = '无牌车';
            } else {
                $record->car_type = '有牌车';
            }
            $record->in_img = config('custom.file_car_img_url').'/'.$record->park_code.'/'.$record->record_id.'_1.jpg';
            $record->out_img = config('custom.file_car_img_url').'/'.$record->park_code.'/'.$record->record_id.'_2.jpg';
            $record->gp_img = config('custom.file_car_img_url').'/'.$record->park_code.'/'.$record->record_id.'_6.jpg';
            // 获取车场记录
            $park_name = ParkChannels::select(['name','arm_code'])->select('park_code',"name",'arm_code','type')->get()->toArray();
            $park_name_arr = [];
            foreach ($park_name as $p) {
                $park_name_arr[$p['park_code']][$p['arm_code']][$p['type']] = $p['name'];
            }
            $record->in_name = ParkChannels::where(['park_code'=>$record->park_code,'arm_code'=>$record->in_arm_code,'type'=>139])
                ->value('name') ?? '';
            $record->out_name = ParkChannels::where(['park_code'=>$record->park_code,'arm_code'=>$record->out_arm_code,'type'=>140])
                ->value('name') ?? '';
            $record->in_time = $record->in_time?date("Y-m-d H:i:s",$record->in_time):'';
            $record->out_time = $record->out_time?date("Y-m-d H:i:s",$record->out_time):'';
        } else {
            return $this->sendError('数据不存在');
        }
        return $this->sendResponse($record, '查询成功');
    }
    /*
     * 车辆追踪列表
     */
    public function VplnRecord(Request $request){
        $input = $request->all();
        $field = $input['field']??'in_time';
        $sort = $input['sort']??'DESC';
        $all_pay_type = config('pay');
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;

        $vpl_number = isset($input['vpl_number'])?$input['vpl_number']:'';
        $vpl_number = strtoupper($vpl_number);
        if(empty($vpl_number)){
            return $this->sendError('不能缺少车牌号');
        }
        $num = findNum($vpl_number);
        if(!is_numeric($num)){
            return $this->sendError('不是有效车牌');
        }
        Schema::connection("park_cloud");
        if((Schema::hasTable("t_vpln_record_$num"))){
            return $this->sendError('没有查到此数据');
        }
        // 获取车场记录
        $park_name = ParkChannels::select(['name','arm_code'])->select('park_code',"name",'arm_code','type')->get()->toArray();
        $park_name_arr = [];
        foreach ($park_name as $p) {
            $park_name_arr[$p['park_code']][$p['arm_code']][$p['type']] = $p['name'];
        }
        if($page==1) {
            // 当前位置
            $v = new VplRecord();

            $v->setTable("t_vpln_record_" . $num);
            // 获取车场范围
            $v = $v->whereIn("park_code", $this->park_arr);
            $car_last_route = $v->where("vpl_number", $vpl_number)->orderBy("in_time", 'desc')->first();
            if (empty($car_last_route)) {
                return $this->sendError('没有此车辆数据');
            }
            if ($car_last_route->status == 1) {
                $car['place'] = '场内';
            } else {
                $car['place'] = '场外';
            }
            $car['vpl_number'] = $vpl_number;
            $car['vpl_owner'] = $car_last_route->vpl_owner;
            $auth_type = config('custom.auth_type');
            $car['car_type'] = $auth_type[$car_last_route->vpl_authtype]??'';
            $car['type'] = $car_last_route->vpl_type;
            $p = $v;
            $car_duration = $p->sum("parking_duration");
            $car['parking_duration'] = sec2time($car_duration);
            $car_fee = $p->sum('parking_charge');
            $car['fee'] = re2float($car_fee / 100);
            $img_url = config('custom.file_car_img_url') . '/' . $car_last_route->park_code . '/' .
                $car_last_route->record_id . '_' . $car_last_route->status . '.jpg';
            $img_info = myGetImageSize($img_url);
            $car['old_img'] = $img_info;
            $car['img'] = $img_url;
            // 总停车次数
            $car['total_num'] = $p->count();
            // 免费停车次数
            $car['free_num'] = $p->where("calc_charge", 0)->where('out_time', '!=', '0')->count();
            $data['car_info'] = $car;
        }
        //
        $v = new VplRecord();
        $v->setTable("t_vpln_record_".$num);
        // 获取车场范围
        $res = $v->whereIn("park_code", $this->park_arr)
            ->where("vpl_number",$vpl_number)->orderBy("id",'desc')->first();
        if(empty($res)){
            return $this->sendError('没有此车牌数据');
        }
        $p = $v->whereIn("park_code", $this->park_arr)
            ->where("is_delete",0)->where("vpl_number",$vpl_number);
        // 时间
        $park_code = isset($input['park_code'])?$input['park_code']:'';
        $parking_charge_min = isset($input['parking_charge_min'])?$input['parking_charge_min']:'';
        $parking_charge_max = isset($input['parking_charge_max'])?$input['parking_charge_max']:'';
        $total_charge_min = isset($input['total_charge_min'])?$input['total_charge_min']:'';
        $total_charge_max = isset($input['total_charge_max'])?$input['total_charge_max']:'';
        $parking_duration_min = isset($input['parking_duration_min'])?$input['parking_duration_min']:'';
        $parking_duration_max = isset($input['parking_duration_max'])?$input['parking_duration_max']:'';
        if(isset($input['start_time']) && !empty($input['start_time'])){
            $start_time_min = $input['start_time'][0]?($input['start_time'][0]):'';
            $start_time_max = $input['start_time'][1]?($input['start_time'][1]):'';
            if($start_time_min){
                $p = $p->where("in_time", '>=' ,$start_time_min);
            }
            if($start_time_max){
                $p = $p->where("in_time", '<=' ,$start_time_max);
            }
        }
        // 出场时间
        if(isset($input['end_time']) && !empty($input['end_time'])){
            $end_time_min = $input['end_time'][0]?($input['end_time'][0]):'';
            $end_time_max = $input['end_time'][1]?($input['end_time'][1]):'';
            if($end_time_min){
                $p = $p->where("out_time", '>=' ,$end_time_min);
            }
            if($end_time_max){
                $p = $p->where("out_time", '<=' ,$end_time_max);
            }
        }

        // 应收金额
        if(!empty($park_code)){
            $p = $p->where("park_code", '=', $park_code);
        }
        // 应收金额
        if(!empty($parking_charge_min)){
            $p = $p->where("calc_charge",">=", $parking_charge_min*100);
        }
        if(!empty($parking_charge_max)){
            $p = $p->where("calc_charge","<=", $parking_charge_max*100);
        }
        // 实收金额
        if(!empty($total_charge_min)){
            $p = $p->where("parking_charge",">=", $total_charge_min*100);
        }
        if(!empty($total_charge_max)){
            $p = $p->where("parking_charge","<=", $total_charge_max*100);
        }
        // 停车时长
        if(!empty($parking_duration_min)){
            $p = $p->where("parking_duration",">=", $parking_duration_min*60);
        }
        if(!empty($parking_duration_max)){
            $p = $p->where("parking_duration","<=", $parking_duration_max*60);
        }
        $num = $p->count();
        $input['num'] = $num;
        $file_name = md5('vpln_'.json_encode($input)).".csv";
        if(isset($input['export']) && !empty($input['export'])) {
            if(file_exists(storage_path("app/public/".$file_name))){
                $res = [];
                $res['file_name'] = $file_name;
                return   $this->sendResponse($res, '查询成功');
            }
            $car_route = $p->get();
        } else {
            $car_route = $p->orderBy($field,$sort)->paginate($pages, array("*"), "page", $page);
        }
        if($car_route){
            $type_arr = config('custom.auth_type');
            $img_num = 0;
            foreach ($car_route as &$val) {
                if($img_num<=10 && empty($car['img']) && $page==1){
                    $img_url = config('custom.file_car_img_url') . '/' . $val->park_code . '/' .
                        $val->record_id . '_' . $val->status . '.jpg';
                    $img_info = myGetImageSize($img_url);
                    $car['img'] = !empty($img_info)?$img_url:'';
                    $img_num++;
                }
                $val->in_name = $park_name_arr[$val->park_code][$val->in_arm_code][139]??'';
                $val->out_name = $park_name_arr[$val->park_code][$val->out_arm_code][140]??'';
                $val->in_time = !empty($val->in_time)?date("Y-m-d H:i:s",$val->in_time):'';
                $val->out_time = !empty($val->out_time)?date("Y-m-d H:i:s",$val->out_time):'';
                $val->parking_duration = sec2time($val->parking_duration);

                $pay_arr = json_decode(stripslashes($val->charge_items), true);
                $val->charge_info = '';
                if($pay_arr) {
                    foreach ( $pay_arr as $v) {
                        $charger = OfflineUser::where("name", $v['charger']??'')->value("true_name");
                        $money_str = '';
                        if(isset($v['account'])){
                            $money_str = "金额：" . (number_format(($v['account']??0) / 100, 2, '.', '')) . "元,";
                        } elseif(isset($v['shishou'])) {
                            if(isset($v['charge_type']) && $v['charge_type'] == 6){
                                $money_str = "面额：" . (sec2time($v['shishou']*60??0,false)) . ",";
                            } else {
                                $money_str = "应收金额：" . (number_format(($v['yingshou']??0) / 100, 2, '.', '')) . "元,
                        实收金额：" . (number_format(($v['shishou']??0)/100, 2, '.', '')) . "元,";
                            }
                        }
                        $val->charge_info .= $money_str."收费类型：" . ($all_pay_type[$v['charge_type']]??'') . ",收费员：" . $charger . "(" . ($v['charger']??0) . "),时间：" . ((isset($v['time']))?date("Y-m-d H:i", $v['time']):'').";";
                    }
                    $val->charge_info = trim($val->charge_info,';');
                } else {
                    $val->charge_info = '';
                }
                $park_name = ParkInfo::where("park_code",$val->park_code)->value("parking_name");
                $val->park_name = $park_name?$park_name:'';
                if(empty($val->out_time)){
                    $val->parking_charge = '';
                    $val->total_charge = '';
                    $val->calc_charge = '';
                    $val->parking_duration = '';
                    $val->out_name = '';
                } else {
                    $val->calc_charge = number_format($val->calc_charge / 100, 2, '.', '');
                    $val->parking_charge = number_format($val->parking_charge / 100, 2, '.', '');
                    $val->total_charge = number_format($val->total_charge / 100, 2, '.', '');
                }
                $val->vpl_type = isset($type_arr[$val->vpl_type])?$type_arr[$val->vpl_type]:'';
            }
        }


        $data['car_route'] = $car_route;
        if(isset($input['export']) && !empty($input['export'])){
            $title = ['park_name'=>'车场名称','in_name'=>'入口名称','in_time'=>'进场时间','out_name'=>'出口名称',
                'out_time'=>'出场时间','parking_duration'=>'停车时长','vpl_type'=>'类型','parking_charge'=>'应收金额(元)',
                'total_chatge'=>'实收金额(元)','charge_info'=>'收费详情'];
            $export_data = [];
            foreach ($car_route as $val) {
                $tmp = [];
                $tmp['park_name'] = $val['park_name'];
                $tmp['in_name'] = $val['in_name'];
                $tmp['in_time'] = $val['in_time'];
                $tmp['out_name'] = $val['out_name'];
                $tmp['out_time'] = $val['out_time'];
                $tmp['parking_duration'] = $val['parking_duration'];
                $tmp['vpl_type'] = $val['vpl_type'];
                $tmp['parking_charge'] = $val['parking_charge'];
                $tmp['total_charge'] = $val['total_charge'];
                $tmp['charge_info'] = $val['charge_info'];
                $export_data[] = $tmp;
            }
            return $this->export($export_data,$title,$file_name);
        }
        if(empty($data)){
            return $this->sendError('没有查到');
        }
        return $this->sendResponse($data, '查询成功');
    }

    /*
     * 车辆追踪列表
     */
    public function VplnInfo(Request $request){
        $input = $request->all();
        $all_pay_type = config('pay');
        $id = $input['id'];
        $vpl_number = isset($input['vpl_number'])?$input['vpl_number']:'';
        if(empty($vpl_number)){
            return $this->sendError('缺少车牌号');
        }
        if(empty($id)){
            return $this->sendError('缺少记录id');
        }
        $num = findNum($vpl_number);
        $v = new VplRecord();
        $v->setTable("t_vpln_record_".$num);
        $val = $v->where("is_delete",0)
            ->where("id",$id)
            ->first();

        // 获取车场记录
        $park_name = ParkChannels::select(['name','arm_code'])->select('park_code',"name",'arm_code','type')->get()->toArray();
        $park_name_arr = [];
        foreach ($park_name as $p) {
            $park_name_arr[$p['park_code']][$p['arm_code']][$p['type']] = $p['name'];
        }
        $val->in_name = ParkChannels::where(['park_code'=>$val->park_code,'arm_code'=>$val->in_arm_code,'type'=>139])
                ->value('name') ?? '';
        $val->out_name = ParkChannels::where(['park_code'=>$val->park_code,'arm_code'=>$val->out_arm_code,'type'=>140])
                ->value('name') ?? '';
        $val->in_time = !empty($val->in_time)?date("Y-m-d H:i:s",$val->in_time):'';
        $val->out_time = !empty($val->out_time)?date("Y-m-d H:i:s",$val->out_time):'';
        if(empty($val->out_time) || empty($val->in_time)){
            $val->parking_duration = '';
        } else {
            $val->parking_duration = sec2time($val->parking_duration);
        }

        $in_img_url = config('custom.file_car_img_url').'/'.$val->park_code.'/'.$val->record_id.'_1.jpg';
        //$img_info = myGetImageSize($in_img_url);
        $val->in_img = $in_img_url;
        $out_img_url = config('custom.file_car_img_url').'/'.$val->park_code.'/'.$val->record_id.'_2.jpg';
        //$img_info = myGetImageSize($out_img_url);
        $val->out_img =  $out_img_url;
        $val->gp_img = config('custom.file_car_img_url').'/'.$val->park_code.'/'.$val->record_id.'_6.jpg';
        $pay_arr = json_decode(stripslashes($val->charge_items), true);
        $val->charge_info = '';
        if($pay_arr) {
            foreach ( $pay_arr as $v) {
                $charger = OfflineUser::where("name", $v['charger']??'')->value("true_name");
                $money_str = '';
                if(isset($v['account'])){
                    $money_str = "金额：" . (number_format(($v['account']??0) / 100, 2, '.', '')) . "元,";
                } elseif(isset($v['shishou'])) {
                    if(isset($v['charge_type']) && $v['charge_type'] == 6){
                        $money_str = "面额：" . (sec2time($v['shishou']*60??0,false)) . ",";
                    } else {
                        $money_str = "应收金额：" . (number_format(($v['yingshou']??0) / 100, 2, '.', '')) . "元,
                        实收金额：" . (number_format(($v['shishou']??0) / 100, 2, '.', '')) . "元,";
                    }
                }
                $val->charge_info .= $money_str."收费类型：" . ($all_pay_type[$v['charge_type']]??'') . ",收费员：" . $charger . "(" . ($v['charger']??0) . "),时间：" . ((isset($v['time']))?date("Y-m-d H:i", $v['time']):'').";";
            }
            $val->charge_info = trim($val->charge_info,';');
        } else {
            $val->charge_info = '';
        }
        $park_name = ParkInfo::where("park_code",$val->park_code)->value("parking_name");
        $val->park_name = $park_name?$park_name:'';

        if(empty($val)){
            return $this->sendError('没有查到');
        }
        return $this->sendResponse($val, '查询成功');
    }

    /**
     * 支付明细列表
     *
     * @param Request $request
     * @return mixed
     */
    public function pay_fee(Request $request)
    {
        $input = $request->all();
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;
        $field = $request->input("field",'id') ;
        $sort = $request->input("sort","desc") ;
        $all_pay_type = config('pay');

        $parking_charge_min = isset($input['parking_charge_min'])?$input['parking_charge_min']:'';
        $parking_charge_max = isset($input['parking_charge_max'])?$input['parking_charge_max']:'';
        $parking_duration_min = isset($input['parking_duration_min'])?$input['parking_duration_min']:'';
        $parking_duration_max = isset($input['parking_duration_max'])?$input['parking_duration_max']:'';
        // 获取车场记录
        $p = new PayFee();


        if(isset($input['vpl_number']) && !empty($input['vpl_number'])){
            $p = $p->where("vpl_number", 'like', '%'.$input['vpl_number'].'%');
        }
        // 车场名称
        if(isset($input['pay_order']) && !empty($input['pay_order'])){
            $p =  $p->where("pay_order", $input['pay_order']);
        }
        // 车场名称
        if(isset($input['pay_src_order']) && !empty($input['pay_src_order'])){
            $p =  $p->where("pay_src_order", $input['pay_src_order']);
        }
        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            foreach ($input['park_code'] as &$val) {
                $val = (string)$val;
            }
            $p =  $p->whereIn("park_code", $input['park_code']);
        } else {
            // 获取车场范围
            $p = $p->whereIn("park_code", $this->park_arr);

        }
        if(isset($input['pay_type']) && is_numeric($input['pay_type'])){
            if($input['pay_type'] == 6){
                $p =  $p->where("pay_order", 'like', "98%");
            } else {
                $p =  $p->where("pay_type", $input['pay_type']);
            }
        }
        if(isset($input['charger']) && is_numeric($input['charger'])){
            $p =  $p->where("charger", $input['charger']);
        }
        // 支付时间
        if(isset($input['pay_time']) && !empty($input['pay_time'])) {
            $pay_time = $input['pay_time'];
            if (isset($pay_time[0]) && !empty($pay_time[0])) {
                $start_time = ($pay_time[0]);
                $p = $p->where("pay_time", '>=', $start_time);
            }
            if (isset($pay_time[1]) && !empty($pay_time[1])) {
                $start_time = ($pay_time[1]);
                $p = $p->where("pay_time", '<', $start_time);
            }
        }
        // 进场时间
        if(isset($input['in_time']) && !empty($input['in_time'])){
            $start_time_min = $input['in_time'][0]?($input['in_time'][0]):'';
            $start_time_max = $input['in_time'][1]?($input['in_time'][1]):'';
            if($start_time_min){
                $p = $p->where("in_time", '>=' ,$start_time_min);
            }
            if($start_time_max){
                $p = $p->where("in_time", '<=' ,$start_time_max);
            }
        }
        // 出场时间
        if(isset($input['end_time']) && !empty($input['end_time'])){
            $end_time_min = $input['end_time'][0]?($input['end_time'][0]):'';
            $end_time_max = $input['end_time'][1]?($input['end_time'][1]):'';
            if($end_time_min){
                $p = $p->where("out_time", '>=' ,$end_time_min);
            }
            if($end_time_max){
                $p = $p->where("out_time", '<=' ,$end_time_max);
            }
        }
        // 应收金额
        if(!empty($parking_charge_min)){
            $p = $p->where("pay_amount",">=", $parking_charge_min*100);
        }
        if(!empty($parking_charge_max)){
            $p = $p->where("pay_amount","<=", $parking_charge_max*100);
        }
        // 停车时长
        if(!empty($parking_duration_min)){
            $p = $p->whereRaw("(out_time-in_time)>=".$parking_duration_min*60);
        }
        if(!empty($parking_duration_max)){
            $p = $p->whereRaw("(out_time-in_time)<=".$parking_duration_max*60);
        }
        $file_name = md5('fee_'.json_encode($input)).".csv";
        if(isset($input['export']) && !empty($input['export'])) {
            if(!isset($input['pay_time']) && !isset($input['end_time'])){
                //return  $this->sendError('请选出场时间范围');
            }
            if(file_exists(storage_path("app/public/".$file_name))){
                $res = [];
                $res['file_name'] = $file_name;
                return   $this->sendResponse($res, '查询成功');
            }
            $count = $p->count();
            if($count > 20000){
                //return  $this->sendError('数据量太多，请缩小时间范围');
            }
            $record = $p->get();
        } else {
            $record = $p->orderBy($field,$sort)->paginate($pages, array("*"), "page", $page);
        }

        $all_pay_type = config('custom.pay_name');
        Schema::connection("local_config");
        foreach ($record as &$val) {
            $val->pay_amount = number_format($val->pay_amount/100,2,'.','');

            // fixed infinity parking time
            $val->parking_duration = $val->out_time && $val->in_time && $val->out_time > $val->in_time ? sec2time($val->out_time-$val->in_time) : '';

            $val->pay_type_name = isset($all_pay_type[$val->pay_type])?$all_pay_type[$val->pay_type]:'';
            if(substr($val->pay_order,0,2) == '98'){
                $val->pay_type_name = '无感支付';
            }
            // 获取车主名
            if(Schema::hasTable("t_card_info_" . $val->park_code)) {
                $v = new CardInfo();
                $v->setTable("t_card_info_" . $val->park_code);
                $park_code = "'%" . trim(json_encode($val->vpl_number), '"') . "%'";
                $owner = $v->where("vpl_number", "like", $park_code)->value("username");
                if (isset($owner) && !empty($owner)) {
                    $val->vpl_owner = $owner ? $owner : '';
                }
            } else {
                $val->vpl_owner = '';
            }
            $val->pay_time = $val->pay_time?date("Y-m-d H:i:s",$val->pay_time):'';
            $val->in_time = $val->in_time?date("Y-m-d H:i:s",$val->in_time):'';
            $val->out_time = $val->out_time?date("Y-m-d H:i:s",$val->out_time):'';
            $park_name = ParkInfo::where("park_code",$val->park_code)->value("parking_name");
            $val->park_name = $park_name?$park_name:'';
            $val->pay_src_amount = number_format($val->pay_src_amount/100,2,'.','');
        }
        if(isset($input['export']) && !empty($input['export'])){
            $title = ['pay_order'=>'订单号','pay_time'=>'支付时间','in_time'=>'车牌号码','park_name'=>'车场名称','out_time'=>'进场时间','parking_duration'=>'出场时间','status'=>'停车时长','parking_charge'=>'车主名称','pay_amount'=>'支付金额（元）','pay_type_name'=>'支付方式','charger'=>'收费员'];
            $type_arr = config('custom.auth_type');
            $export_data = [];
            foreach ($record as $val) {
                $tmp = [];
                $tmp['pay_order'] = $val['pay_order'];
                $tmp['pay_time'] = $val['pay_time'];
                $tmp['vpl_number'] = $val['vpl_number'];
                $tmp['park_name'] = $val['park_name'];
                $tmp['in_time'] = $val['in_time'];
                $tmp['out_time'] = $val['out_time'];
                $tmp['parking_duration'] = $val['parking_duration'];
                $tmp['vpl_owner'] = $val['vpl_owner'];
                $tmp['pay_amount'] = $val['pay_amount'];
                $tmp['pay_type_name'] = $val['pay_type_name'];
                $tmp['charger'] = $val['charger'];
                $export_data[] = $tmp;
            }
            return $this->export($export_data,$title,$file_name);
        }
        return $this->sendResponse($record, '查询成功');
    }

    function down(Request $request){
        header('Access-Control-Allow-Origin:*');
        $file_name = $request->input("file_name");
        $new_name = $request->input("new_name",'');
        $subffix = substr($new_name,strpos($new_name,'.')+1);
        if($new_name && $subffix != 'csv'){
            return $this->sendError('新文件名后缀必须是csv');
        }
        if(empty($file_name)){
            return $this->sendError('缺少文件名');
        }
        $file = storage_path("app/public/".$file_name);
        if(empty($new_name)) $new_name = $file_name;
        downfile($file, $new_name);
    }

    function badCar(Request $request){
        $input = $request->all();
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;

        // 获取车场记录
        $p = new BadCarLog();

        if(isset($input['vpl_number']) && !empty($input['vpl_number'])){
            $p = $p->where("vpl_number", 'like', '%'.$input['vpl_number'].'%');
        }
        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $p =  $p->where("park_code", $input['park_code']);
        } else {
            $p = $p->whereIn("park_code", $this->park_arr);
        }
        // 车主姓名
        if(isset($input['vpl_owner']) && !empty($input['vpl_owner'])){
            $p =  $p->where("vpl_owner", 'like', $input['vpl_owner']);
        }
        // 车辆状态
        if(isset($input['status']) && is_numeric($input['status'])){
            $p =  $p->where("status", $input['status']);
        }
        // 进场时间
        if(isset($input['in_time']) && !empty($input['in_time'])){
            $start_time_min = $input['in_time'][0]?($input['in_time'][0]):'';
            $start_time_max = $input['in_time'][1]?($input['in_time'][1]):'';
            if($start_time_min){
                $p = $p->where("in_time", '>=' ,$start_time_min);
            }
            if($start_time_max){
                $p = $p->where("in_time", '<=' ,$start_time_max);
            }
        }
        // 出场时间
        if(isset($input['out_time']) && !empty($input['out_time'])){
            $end_time_min = $input['out_time'][0]?($input['out_time'][0]):'';
            $end_time_max = $input['out_time'][1]?($input['out_time'][1]):'';
            if($end_time_min){
                $p = $p->where("out_time", '>=' ,$end_time_min);
            }
            if($end_time_max){
                $p = $p->where("out_time", '<=' ,$end_time_max);
            }
        }
        $record = $p->paginate($pages,array("*"),"page",$page);
        $type_arr = config('custom.auth_type');
        // 获取车场记录
        $park_name = ParkChannels::select(['name','arm_code'])->select('park_code',"name",'arm_code','type')->get()->toArray();
        $park_name_arr = [];
        foreach ($park_name as $p) {
            $park_name_arr[$p['park_code']][$p['arm_code']][$p['type']] = $p['name'];
        }
        $all_pay_type = config('pay');
        Schema::connection("local_config");
        foreach ($record as &$val) {
            // $val->parking_duration = ($val->out_time-$val->in_time)>0?sec2time($val->out_time-$val->in_time):'0分钟';

            // fixed infinity parking time
            $val->parking_duration = $val->out_time && $val->in_time && $val->out_time > $val->in_time ? sec2time($val->out_time-$val->in_time) : '';

            $val->pay_type_name = isset($all_pay_type[$val->pay_type])?$all_pay_type[$val->pay_type]:'';
            // 获取车主名
            if(Schema::hasTable("t_card_info_" . $val->park_code)) {
                $v = new CardInfo();
                $v->setTable("t_card_info_" . $val->park_code);
                $park_code = "'%" . trim(json_encode($val->vpl_number), '"') . "%'";
                $owner = $v->where("vpl_number", "like", $park_code)->value("username");
                if (isset($owner) && !empty($owner)) {
                    $val->vpl_owner = $owner ? $owner : '';
                }
            } else {
                $val->vpl_owner = '';
            }
            $pay_arr = json_decode(stripslashes($val->charge_items), true);
            if($pay_arr) {
                $pay_info = $pay_arr[0];
                $charger = OfflineUser::where("name",(isset($pay_info['charger'])?$pay_info['charger']:''))->value("true_name");
                $charger = $charger??'';
                if ($val->charge_items) {
                    $money_str = '';
                    if(isset($v['account'])){
                        $money_str = "金额：" . (number_format(($v['account']??0) / 100, 2, '.', '')) . "元,";
                    } elseif(isset($v['shishou'])) {
                        if(isset($v['charge_type']) && $v['charge_type'] == 6){
                            $money_str = "面额：" . (sec2time($v['shishou']*60??0,false)) . ",";
                        } else {
                            $money_str = "应收金额：" . (number_format(($v['yingshou']??0) / 100, 2, '.', '')) . "元,
                        实收金额：" . (number_format(($v['shishou']??0) / 100, 2, '.', '')) . "元,";
                        }
                    }
                    $val->charge_info = $money_str."收费类型：" .(isset($all_pay_type[$pay_info['charge_type']])?$all_pay_type[$pay_info['charge_type']]:'')  .
                        ",收费员：" . $charger . "(".$pay_info['charger']."),时间：" . date("Y-m-d H:i", $pay_info['time']);
                } else {
                    $val->charge_info = '';
                }
            } else {
                $val->charge_info = '';
            }
            $val->in_name = $park_name_arr[$val->park_code][$val->in_arm_code][139]??'';
            $val->out_name = $park_name_arr[$val->park_code][$val->out_arm_code][140]??'';
            $val->pay_time = $val->pay_time?date("Y-m-d H:i:s",$val->pay_time):'';
            $val->in_time = $val->in_time?date("Y-m-d H:i:s",$val->in_time):'';
            $val->out_time = $val->out_time?date("Y-m-d H:i:s",$val->out_time):'';
            $park_arr = ParkInfo::where("park_code",$val->park_code)->value("parking_name");
            $val->park_name = $park_arr?$park_arr:'';
            if(empty($val->out_time)) {
                $val->parking_charge = '';
                $val->calc_charge = '';
                $val->total_charge = '';
                $val->parking_duration = '';
            } else  {
                $val->parking_charge = number_format($val->parking_charge / 100, 2, '.', '');
                $val->calc_charge = number_format($val->calc_charge / 100, 2, '.', '');
                $val->total_charge = number_format($val->total_charge / 100, 2, '.', '');
            }
            $val->vpl_type = isset($type_arr[$val->vpl_type])?$type_arr[$val->vpl_type]:'';
        }
        return $this->sendResponse($record, '查询成功');
    }

    /*
     *  不良车信息
     */
    public function badCarInfo(Request $request){
        $id = $request->input('id');
        $park_code = $request->input('park_code');
        if(empty($id)){
            return $this->sendError('id不能为空');
        }

        $p = new BadCarLog();
        $record = $p->find($id);
        if($record) {
            if (strlen($record->vpl_number) >= 15 || empty($record->vpl_number)) {
                $record->car_type = '无牌车';
            } else {
                $record->car_type = '有牌车';
            }
            $record->in_img = config('custom.file_car_img_url').'/'.$record->park_code.'/'.$record->record_id.'_1.jpg';
            $record->out_img = config('custom.file_car_img_url').'/'.$record->park_code.'/'.$record->record_id.'_2.jpg';
            // 获取车场记录
            $park_name = ParkChannels::select(['name','arm_code'])->select('park_code',"name",'arm_code','type')->get()->toArray();
            $park_name_arr = [];
            foreach ($park_name as $p) {
                $park_name_arr[$p['park_code']][$p['arm_code']][$p['type']] = $p['name'];
            }
            $record->in_name = ParkChannels::where(['park_code'=>$record->park_code,'arm_code'=>$record->in_arm_code,'type'=>139])
                    ->value('name') ?? '';
            $record->out_name = ParkChannels::where(['park_code'=>$record->park_code,'arm_code'=>$record->out_arm_code,'type'=>140])
                    ->value('name') ?? '';
            $record->in_time = $record->in_time?date("Y-m-d H:i:s",$record->in_time):'';
            $record->out_time = $record->out_time?date("Y-m-d H:i:s",$record->out_time):'';
        } else {
            return $this->sendError('数据不存在');
        }
        return $this->sendResponse($record, '查询成功');
    }

    /*
     *  停车记录模糊查询列表
     */
    public function recordNumberList(Request $request){
        $input = $request->all();
        $input['park_code'] = $input['park_code']??'';
        $input['vpl_number'] = $input['vpl_number']??'';
        $input['vpl_number'] = strtoupper($input['vpl_number']);
        // 获取车场记录
        $park_name = ParkChannels::select(['name','arm_code'])->select('park_code',"name",'arm_code','type')->get()->toArray();
        $park_name_arr = [];
        foreach ($park_name as $p) {
            $park_name_arr[$p['park_code']][$p['arm_code']][$p['type']] = $p['name'];
        }
        $p = new ParkRecord();
        $p->setTable("t_park_record_{$input['park_code']}");

        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $p = $p->where("park_code", $input['park_code']);
        } else {
            return $this->sendError('车场不能为空');
        }
        if(isset($input['vpl_number'])){
            $p = $p->where("vpl_number", 'like', '%'.$input['vpl_number'].'%');
        } else {
            return $this->sendError('车牌好不能为空');
        }
        $record = $p->select("vpl_number")->distinct()->orderBy("id",'desc')->limit(100)->get();

        return $this->sendResponse($record, '查询成功');
    }
    /*
     *  车辆追踪模糊查询列表
     */
    public function vplNumberList(Request $request){
        $input = $request->all();
        $input['vpl_number'] = $input['vpl_number']??'';
        $input['vpl_number'] = strtoupper($input['vpl_number']);
        if(empty($input['vpl_number'])){
            return $this->sendError('车场不能为空和0');
        }
        $vpl_number = $input['vpl_number'];
        $num = findNum($vpl_number);
        if(!is_numeric($num)){
            return $this->sendError('不是有效车牌');
        }
        Schema::connection("park_cloud");
        if((Schema::hasTable("t_vpln_record_$num"))){
            return $this->sendError('没有查到此数据');
        }
        //
        $v = new VplRecord();
        $v->setTable("t_vpln_record_".$num);
        $v = $v->whereIn("park_code", $this->park_arr);
        $v = $v->where("vpl_number", 'like', '%'.$input['vpl_number'].'%');
        $record = $v->select("vpl_number")->distinct()->orderBy("id",'desc')->limit(50)->get();

        return $this->sendResponse($record, '查询成功');
    }

    /*
     *  车场管家车辆
     *
     */
    public function mvplNumberList(Request $request){
        $input = $request->all();
        $vpl_number = $input['vpl']??'';
        $park_code = $input['park']??'';
        if(empty($vpl_number)){
            return $this->sendError('车场不能为空和0');
        }
        $vpl_number = strtoupper($vpl_number);
        $num = findNum($vpl_number);
        if(!is_numeric($num)){
            return $this->sendError('不是有效车牌');
        }
        Schema::connection("park_cloud");
        if((Schema::hasTable("t_vpln_record_$num"))){
            return $this->sendError('没有查到此数据');
        }
        //
        $v = new VplRecord();
        $v->setTable("t_vpln_record_".$num);
        $v = $v->where("vpl_number", 'like', '%'.$vpl_number.'%');
        if(!empty($park_code))  {
            $v = $v->where("park_code", $park_code);
        }
        $record = $v->select([
            'vpl_number', 'in_time', 'park_code', 'record_id', 'in_arm_code',
            'trace_uk', 'depot_id', 'vpl_type', 'vpl_color', 'update_time',
            ])
            ->distinct()
            ->orderBy("id",'desc')
            ->limit(5)
            ->get();

        exit(json_encode(["data"=>$record,"code"=>0,"message"=>"获取成功"]));
    }

    function getVideo(Request $request){
        $data = $request->all();
        if(empty($data['park_code'])){
            return $this->sendError('车场不能为空和0');
        }
        if(!isset($data['arm_code'])){
            return $this->sendError('arm_code不能为空');
        }
        if(empty($data['device_type'])){
            return $this->sendError('设备类型不能为空');
        }
        if(empty($data['gate_type'])){
            return $this->sendError('出入口参数不能为空');
        }
        $res = Video::where("park_code",$data['park_code'])
            ->where("arm_code",$data['arm_code'])
            ->where("device_type",$data['device_type'])
            ->where("gate_type",$data['gate_type'])
            ->first();
        if(empty($res)){
            $res = [];
        }
        return $this->sendResponse($res, '查询成功');
    }

}
